/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 *
 * @format
 * @flow
 */

import React, {Component} from 'react';
import {
    View,
    Platform,
    BackHandler, AsyncStorage, StatusBar, ToastAndroid
} from 'react-native';
import {connect} from 'react-redux';
import DropdownAlert from "react-native-dropdownalert";
import {NavigationActions, StackActions} from "react-navigation";

import AppNavigator from './src/router/LoginNavigator'
import CodePushModal from './src/component/CodePushView/CodePushView'
import {doRemoveMessage, doShowMessage} from "./src/component/Message/Action"
import {getStore} from "./src/configuration/StoreConfiguration"
import {JPushOnListening, JPushUnmount} from "./src/util/JPush/JPushUtil"
import global from "./src/configuration/global"
import JPushModule from "jpush-react-native";
import codePush from 'react-native-code-push';
import {COLOR_GRAY_BACKGROUND} from './src/constant/PHColors'

type Props = {};

let codePushOptions = {
    //设置检查更新的频率
    //ON_APP_RESUME APP恢复到前台的时候
    //ON_APP_START APP开启的时候
    //MANUAL 手动检查
    checkFrequency : codePush.CheckFrequency.ON_APP_RESUME
};

class App extends Component<Props> {

    // 构造
    constructor(props) {
        super(props);

        this.syncMessage = '';
        // 初始状态
        // this.state = {
        //     JPushModalVisiable:false,
        //     WebSocketData:[],
        //     userid:'',
        // };
        //
        // setInterval(() => {
        //     User.getUser(user => {
        //         if (user&&user.token) {
        //             let WebSocketData_new = global.WebSocketData;
        //             if(JSON.stringify(WebSocketData_new) !== JSON.stringify(this.state.WebSocketData) && JSON.stringify(WebSocketData_new)!== '[]'){
        //                 this.setState({
        //                     WebSocketData: WebSocketData_new,
        //                     JPushModalVisiable:true,
        //                     userid:user.userid
        //                 })
        //             }
        //         }
        //     })
        // }, 3000)
    }

  initBackButton = () => {
    if (Platform.OS !== 'android') return;
    BackHandler.addEventListener('hardwareBackPress', this.onBackButton);
  };

  onBackButton = () => {
    const state = getStore().getState();
    const navigationState = state.navState;   // < the name of your reducer

    if (navigationState && navigationState.index) {
      getStore().dispatch(NavigationActions.back());
      return true;  // will not exit, just go back
    } else {
      return false;   // will exit
    }
  };

    //如果有更新的提示
    syncImmediate() {
        codePush.sync(
            {
                //安装模式
                //ON_NEXT_RESUME 下次恢复到前台时
                //ON_NEXT_RESTART 下一次重启时
                //IMMEDIATE 马上更新
                installMode : codePush.InstallMode.IMMEDIATE ,
                //对话框
                updateDialog : {
                    //是否显示更新描述
                    appendReleaseDescription : true ,
                    //更新描述的前缀。 默认为"Description"
                    descriptionPrefix : "更新内容：" ,
                    //强制更新按钮文字，默认为continue
                    mandatoryContinueButtonLabel : "立即更新" ,
                    //强制更新时的信息. 默认为"An update is available that must be installed."
                    mandatoryUpdateMessage : "必须更新后才能使用" ,
                    //非强制更新时，按钮文字,默认为"ignore"
                    optionalIgnoreButtonLabel : '稍后' ,
                    //非强制更新时，确认按钮文字. 默认为"Install"
                    optionalInstallButtonLabel : '后台更新' ,
                    //非强制更新时，检查到更新的消息文本
                    optionalUpdateMessage : '有新版本了，是否更新？' ,
                    //Alert窗口的标题
                    title : '更新提示'
                } ,
            },
            this.codePushStatusDidChange.bind(this)
        );
    }

    componentWillMount() {
        // codePush.disallowRestart();//禁止重启
        this.syncImmediate(); //开始检查更新
    }

    codePushStatusDidChange(syncStatus) {
        switch(syncStatus) {
            case codePush.SyncStatus.CHECKING_FOR_UPDATE:
                this.syncMessage = '检查更新'
                break;
            case codePush.SyncStatus.DOWNLOADING_PACKAGE:
                this.syncMessage = '正在下载'
                // ToastAndroid.show(this.syncMessage,1000);
                break;
            case codePush.SyncStatus.AWAITING_USER_ACTION:
                this.syncMessage = 'Awaiting user action'
                break;
            case codePush.SyncStatus.INSTALLING_UPDATE:
                this.syncMessage = '正在安装...'
                // ToastAndroid.show(this.syncMessage,1000);
                break;
            case codePush.SyncStatus.UP_TO_DATE:
                this.syncMessage = '已是最新版本!'
                break;
            case codePush.SyncStatus.UPDATE_IGNORED:
                this.syncMessage = '更新失败，请重启应用!'
                ToastAndroid.show(this.syncMessage,3000);
                break;
            case codePush.SyncStatus.UPDATE_INSTALLED:
                this.syncMessage = '更新完成!'
                ToastAndroid.show(this.syncMessage,2000);
                break;
            case codePush.SyncStatus.UNKNOWN_ERROR:
                this.syncMessage = 'An unknown error occurred'
                // ToastAndroid.show('更新出错，请重启应用！',1000)
                break;
        }
    }

  componentDidMount() {

      codePush.allowRestart();//在加载完了，允许重启

    this.initBackButton();

    AsyncStorage.getItem("ProductAPIUrl").then((valueProductAPIUrl) => {
        global.AppRequestPath=valueProductAPIUrl
    })

      // AsyncStorage.getItem("ProductAPIUrl_spare").then((valueProductAPIUrl_spare) => {
      //     global.AppRequestPath_spare=valueProductAPIUrl_spare
      // })

    AsyncStorage.getItem("hotelId").then((value) => {
        global.hotelId=value;
    })

    // 极光推送
    JPushOnListening(
      (aaa) => {
          console.log("极光推送"+aaa)
      },
      (bbb) => {
          console.log("极光推送"+bbb)
      },
      (ccc) => {
          console.log("极光推送"+ccc)
      }
    )

      JPushModule.getRegistrationID(registrationId => {
          // console.log("getRegistrationID====="+registrationId);
      })

      // JPushModule.addReceiveNotificationListener(map => {
      //     // console.log('alertContent: ' + map.alertContent);
      //     // console.log('extras: ' + map.extras);
      //     // alert('alertContent: ' + map.alertContent);
      //     // var extra = JSON.parse(map.extras);
      //     console.log(map);
      //     this.setState({
      //         JPushModalVisiable:true,
      //     })
      // });

      JPushModule.addReceiveOpenNotificationListener(map => {
          // console.log('alertContent: ' + map.alertContent);
          // console.log('extras: ' + map.extras);
          // alert('alertContent: ' + map.alertContent);
          // var extra = JSON.parse(map.extras);
          console.log("aaaaa====="+map);
          global.WebSocketData.random = Math.random();

          // const {navigate} = this.props.navigation;
          // navigate("RoomStatusScreen")
      });



  }

  componentWillUnmount(): void {
    // 激光推送
    JPushUnmount();

  }

  componentWillReceiveProps(nextProps, nextContext) {
    let {dispatch} = this.props;
    if (nextProps.onMessage !== this.props.onMessage) {
      doShowMessage(nextProps.onMessage, this.dropdown);
    }
  }

  render(): React.ReactNode {
    return (
      <View style={{flex: 1}}>
        <StatusBar barStyle={'dark-content'} backgroundColor={'#f2f2f2'}/>

        <AppNavigator/>

        <DropdownAlert ref={ref => this.dropdown = ref}
                       defaultContainer={{padding: 8, paddingTop: Platform.OS === 'android' ? 0 : 40, flexDirection: 'row'}}
                       closeInterval={2000}
                       errorColor='#f13838'
                       onClose={() => {
                         let {dispatch} = this.props;
                         dispatch(doRemoveMessage());
                       }}
        />

        {/*<JPushModal JPushModalVisiable={this.state.JPushModalVisiable} JPushText={'cs'} WebSocketData={this.state.WebSocketData}
                    CloseJPushModal={()=>{
                        this.onCloseJPushModal()
                    }}
        />*/}
        {/*<CodePushModal />*/}
      </View>
    );
  }

    /*onCloseJPushModal(){
        this.setState({
            JPushModalVisiable:false
        })
    }*/

}

const props = state => {
  return {
    onMessage: state.onMessage
  }
};

App = codePush(codePushOptions)(App);
export default connect(props)(App);
